#ifndef HC_TREE_VIEW_MODEL_H
#define HC_TREE_VIEW_MODEL_H

#include <QAbstractItemModel>
#include <QBrush>
#include <QFont>

// struct TreeStruct {
//   int id_{0};
//   int parentId_{0};
//   QString name_;
//   QString type_;
// };

struct TreeClickItem {
  int topic_ = -1;
  int domain_ = -1;
  int paramter_ = -1;
  QString domainStruct_ = "";
  QString opticName_ = "";
  QString name_ = "aaaaaaaaa";

  bool operator==(const TreeClickItem &tarItem) {
    return topic_ == tarItem.topic_ && domain_ == tarItem.domain_ &&
           paramter_ == tarItem.paramter_ &&
           domainStruct_ == tarItem.domainStruct_ &&
           opticName_ == tarItem.opticName_ && name_ == tarItem.name_;
  }
};

class TreeNode {
 public:
  TreeClickItem data_;          // 存储节点数据
  QList<TreeNode *> children_;  // 子节点列表
  TreeNode *parent_{nullptr};   // 父节点
  QFont customFont_;            // 字体
  QColor textColor_;            // 字体颜色
  bool isDisabled_{false};      // 是否显示
  TreeNode(const TreeClickItem &data, TreeNode *parent = nullptr)
      : data_(data), parent_(parent) {}

  void addChild(TreeNode *child) { children_.append(child); }

  void removeChild(TreeNode *child) { children_.removeAll(child); }

  int childCount() const { return children_.size(); }

  TreeNode *child(int row) const { return children_.value(row); }

  int row() const {
    if (parent_ != nullptr) {
      return parent_->children_.indexOf(const_cast<TreeNode *>(this));
    }
    return 0;
  }
};

class TreeModel : public QAbstractItemModel {
  Q_OBJECT
 public:
  TreeModel(QObject *parent = nullptr) : QAbstractItemModel(parent) {
    rootNode_ = new TreeNode(TreeClickItem());  // 创建根节点
  }

  ~TreeModel() { delete rootNode_; }
  // 外部初始化节点
  void InitRootNode(TreeNode *rootNode);

  // 添加树节点
  void AddTree(const TreeClickItem &parentItem, const TreeClickItem &item);
  // 移除树节点
  void MoveItem(const TreeClickItem &item);
  // 编辑节点
  void EditItem(const TreeClickItem &item);
  // 找到指定节点
  TreeNode *FindNodeByItem(const TreeClickItem &item);

 signals:
  void nodeClicked(int id);

 protected:
  QModelIndex index(int row, int column,
                    const QModelIndex &parent) const override;

  QModelIndex parent(const QModelIndex &index) const override;
  int rowCount(const QModelIndex &parent = QModelIndex()) const override;
  int columnCount(const QModelIndex &parent = QModelIndex()) const override;
  QVariant data(const QModelIndex &index, int role) const override;
  bool setData(const QModelIndex &index, const QVariant &value,
               int role) override;
  Qt::ItemFlags flags(const QModelIndex &index) const override;

 private:
  TreeNode *rootNode_;  // 根节点
  // 递归查找节点
  TreeNode *findNodeByItem(TreeNode *node, const TreeClickItem &targetItem);
};

#endif  // HC_TREE_VIEW_MODEL_H
